<?php

namespace App\Service\playlet;
use App\Model\DataUser;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class DataUserService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;
    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = DataUser::query()->select(['id','username','real_name','phone','created_at','updated_at']);


        if ($keyword) {
            $query->orWhere([['username', 'like', '%'.$keyword.'%']])->orWhere([['real_name', 'like', '%'.$keyword.'%']]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        return $models;
    }


    public function createOrUpdate(Array $postData,bool $is_update = false,DataUser $userInfo = null){
        $password = $postData['password'] ?? '';
        $password_repeat = $postData['password_repeat'] ?? '';
        $username = $postData['username'];
        $real_name = $postData['real_name'];
        $phone = $postData['phone'] ?? '';
        $is_check_user = true;
        $is_check_password = true;
        $model = !empty($userInfo)? $userInfo : new DataUser();
        //修改
        if($is_update) {
            //修改时判断用户名是否一致
            if ($username == $userInfo->username) {
                $is_check_user = false;
            }
        }
        //检查是否有重名
        if($is_check_user){
            $userInfo = DataUser::query()->where('username',$username)->first();
            if(!empty($userInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '用户名已存在');
            }
            $model->username = $username;
        }
        //检查密码是否需要修改
        if($is_update) {
            //修改时判断用户名是否一致
            if (empty($password)) {
                $is_check_password = false;
            }
        }
        if($is_check_password){
            if($password_repeat != $password){
                return $this->response(SystemCode::SYSTEM_ERROR, '密码不一致');
            }
            $model->password = md5($password);
        }
        $model->phone = $phone;
        $model->real_name = $real_name;
        if($model->save()){
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }

}